<?php
namespace app\work\controller;

use app\common\controller\Work;
use app\common\library\util\Token;
use app\common\model\Business\Business as BusinessBusiness;
use app\common\model\Business\Source;
use app\common\model\Order\Product;
use fast\Http;
use fast\Random;
use think\Request;
use Exception;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;
use think\File;

class Business extends Work
{
    protected $model = null;
    protected $orderProductModel = null;
    public function __construct(Request $request)
    {
        $this->noLogin = ['wxlogin','weblogin'];
        $this->model = new BusinessBusiness();
        $this->orderProductModel = new Product();
        parent::__construct($request);
    }
    public function WxLogin()
    {
        $code = $this->request->param('code','');
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $params = [
            'appid'=>'wx68dbf57e23156ce9',
            'secret'=>'79133b04ba8136eb3404569fe2bf24c1',
            // 'appid'=>'wx46ddf853a397a17f',
            // 'secret'=>'138bc799b3ef7b92135e8b5e4c96f2f3',
            'js_code'=>$code,
            'grant_type'=>'authorization_code',
        ];
        $result = json_decode(Http::get($url,$params));
        if(isset($result->errcode)){
            $this->error($result->errmsg);
        }
        $business = $this->model->where('openid',$result->openid)->find();
        if($business)
        {
            $token = Token::generateToken([
                "id" => $business["id"],
                "mobile" => $business["mobile"],
            ]);
            $data = [
                'token'=>$token,
                'business'=>$business,
            ];
            $this->success('',null,$data);
        }
        $data = [
            'action'=>'bind',
            'openid'=>$result->openid,
        ];
        $this->success('',null,$data);
    }
    public function WxBind()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $mobile = $this->request->param('mobile','');
        $passwordInput = $this->request->param('password','');
        $openid = $this->request->param('openid','');
        $business = $this->model->where('mobile',$mobile)->find();
        $result = [];
        if($business){
            $password = $business["password"];
            $salt = $business["salt"];
            if(md5(md5($passwordInput) . $salt)==$password){
                $business['openid'] = $openid;
                $result = $business->isUpdate()->save();
                if($result===false)$this->error('登录失败');
                $token = Token::generateToken([
                    "id" => $business["id"],
                    "mobile" => $business["mobile"],
                ]);
                $data = [
                    'business'=>$business,
                    'token'=>$token,
                ];
                $this->success('登录成功',null,$data);
            }else{
                $this->error('登录失败');
            }
        }else{
            $nickname = substr($mobile,0,3).'****'.substr($mobile,strlen($mobile)-4,strlen($mobile));
            $salt = Random::alnum(10);
            $password = md5(md5($passwordInput) . $salt);
            $sourceid = Source::whereLike('name','%防伪查询%')->find()['id'];
            $data = [
                'mobile' => $mobile,
                'nickname' => $nickname,
                'password' => $passwordInput,
                'salt' => $salt,
                'gender' => 0,
                'sourceid' => $sourceid,
                'deal' => 0,
                'money' => 0,
                'auth' => 0,
                'openid'=>$openid,
            ];
            $result = false;
            Db::startTrans();
            try {
                $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $this->validateFailException()->validate($data,$validate);
                $data['password'] = $password;
                $result = $this->model->create($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error('注册失败');
            }else{
                $token = Token::generateToken([
                    "id" => $result["id"],
                    "mobile" => $result["mobile"],
                ]);
                $data = [
                    'business'=>$business,
                    'token'=>$token,
                ];
                $this->success('注册成功',null,$data);
            }
        }
    }
    public function UnBind()
    {
        $busid = $this->request->param('id');
        $business = $this->model->get($busid);
        $business['openid'] = null;
        $result = $business->isUpdate()->save();
        $result===false?$this->error('解绑失败'):$this->success('解绑成功');
    }
    public function Check()
    {
        $token = $this->request->param('token','');
        $result = parent::isLogin($token);
        $result['code']==0?$this->error($result['msg']):$this->success($result['msg'],null,$result['data']);
    }
    public function WebLogin()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $mobile = $this->request->param('mobile','');
        $passwordInput = $this->request->param('password','');
        $business = $this->model->where('mobile',$mobile)->find();
        $result = [];
        if($business){
            $password = $business["password"];
            $salt = $business["salt"];
            if(md5(md5($passwordInput) . $salt)==$password){
                $token = Token::generateToken([
                    "id" => $business["id"],
                    "mobile" => $business["mobile"],
                ]);
                $data = [
                    'business'=>$business,
                    'token'=>$token,
                ];
                $this->success('登录成功',null,$data);
            }else{
                $this->error('登录失败');
            }
        }else{
            $nickname = substr($mobile,0,3).'****'.substr($mobile,strlen($mobile)-4,strlen($mobile));
            $salt = Random::alnum(10);
            $password = md5(md5($passwordInput) . $salt);
            $sourceid = Source::whereLike('name','%防伪查询%')->find()['id'];
            $data = [
                'mobile' => $mobile,
                'nickname' => $nickname,
                'password' => $passwordInput,
                'salt' => $salt,
                'gender' => 0,
                'sourceid' => $sourceid,
                'deal' => 0,
                'money' => 0,
                'auth' => 0,
            ];
            $result = false;
            Db::startTrans();
            try {
                $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $this->validateFailException()->validate($data,$validate);
                $data['password'] = $password;
                $result = $this->model->create($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error('注册失败');
            }else{
                $token = Token::generateToken([
                    "id" => $result["id"],
                    "mobile" => $result["mobile"],
                ]);
                $data = [
                    'business'=>$business,
                    'token'=>$token,
                ];
                $this->success('注册成功',null,$data);
            }
        }
    }
    public function ProductIndex()
    {
        $busid = $this->request->param('busid',0);
        $keyword = $this->request->param('keyword','');
        $page = $this->request->param('page',1);
        $pageSize = $this->request->param('pageSize',1);
        $where = ['product.busid'=>$busid,'productProduct.name'=>['like','%'.$keyword.'%']];
        $list = $this->orderProductModel
                ->with(['productProduct'])
                ->where('product.status','>=','2')
                ->where($where)
                ->order('createtime','desc')
                ->paginate($pageSize,$page);
        // return $this->orderProductModel->getLastSql();
        return $list;
    }
    public function ProductInfo()
    {
        $code = $this->request->param('code','');
        $orderProduct = $this->orderProductModel
                ->with(['productProduct'])
                ->where('product.status','>=','2')
                ->where('product.query_code',$code)
                ->find();
        if(!$orderProduct)$this->error('查无商品');
        $prefilename = ROOT_PATH.'public'.$orderProduct['query_qrcord'];
        if(is_file($prefilename)){
            $orderProduct['query_num'] = $orderProduct['query_num']?$orderProduct['query_num']+1:1;
            if($orderProduct['query_num']==1){
                $orderProduct['query_time'] = time();
            }
            $result = $orderProduct->isUpdate()->save();
            $result===false?$this->error('查无商品'):$this->success('',null,$orderProduct);
        }
        
        $code = $this->request->param('code','');
        $url = 'https://api.weixin.qq.com/cgi-bin/token';
        $params = [
            'appid'=>'wx68dbf57e23156ce9',
            'secret'=>'79133b04ba8136eb3404569fe2bf24c1',
            'grant_type'=>'client_credential',
        ];
        $result = json_decode(Http::post($url,$params));

        $access_token = $result->access_token;
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token";
        $params = [
            'path'=>"/pages/validate/info?code=$code",
            "width"=>100
        ];
        $result = Http::post($url,json_encode($params));
        $dirname = '/uploads/'.date('Ymd');
        $query_qrcord = $dirname.'/'.Random::alnum(32).'.jpg';
        $dirname = ROOT_PATH.'public'.$dirname;
        if(!is_dir($dirname)){
            $result = mkdir($dirname);
            if(!$result)$this->error('查询出错');
        }
        $filename = ROOT_PATH.'public'.$query_qrcord;
        $result = file_put_contents($filename,$result);
        if($result){
            @unlink($prefilename);
            $orderProduct['query_num'] = $orderProduct['query_num']?$orderProduct['query_num']+1:0;
            if($orderProduct['query_num']==1){
                $orderProduct['query_time'] = time();
            }
            $orderProduct['query_qrcord'] = $query_qrcord;
            $result = $orderProduct->isUpdate()->save();
            !$orderProduct&&$result===false?$this->error('查无商品'):$this->success('',null,$orderProduct);
        }
        $this->error('查询出错');
    }
    public function GenerateCode()
    {
        $code = $this->request->param('code','');
        $orderProduct = $this->orderProductModel
                ->with(['productProduct'])
                ->where('product.status','>=','2')
                ->where('product.query_code',$code)
                ->find();
        $orderProduct['query_code'] = 'UNID'.strtoupper(Random::alnum(18));
        $orderProduct['query_qrcord'] = null;
        $result = $orderProduct->isUpdate()->save();
        $result===false?$this->error('更改失败'):$this->success('',null,$orderProduct);
    }
}
